import React, { useCallback, useState, } from 'react';
import Child from '../components/child';
import ChildMemo from '../components/child-memo';
import JSEncrypt from 'jsencrypt';

export default (props = {}) => {
    const [step, setStep] = useState(0);
    const [count, setCount] = useState(0);
    const [number, setNumber] = useState(0);
    const [value, setValue] = useState('');
    const [value2, setValue2] = useState('');

    const handleSetStep = () => {
        setStep(step + 1);
    };

    const handleSetCount = () => {
        setCount(count + 1);
    };

    const handleCalNumber = () => {
        setNumber(count + step);
    };

    const onEncode = useCallback(() => {
        const encryptor = new JSEncrypt();// 创建加密对象实例
        //之前ssl生成的公钥，复制的时候要小心不要有空格
        encryptor.setPublicKey(value);//设置公钥
        const rsaPassWord = encryptor.encrypt(value2);

        setValue2(rsaPassWord);
    }, [value, value2, setValue2]);

    const onDecode = useCallback(() => {
        const decrypt = new JSEncrypt();//创建解密对象实例
        //之前ssl生成的秘钥
        decrypt.setPrivateKey(value);//设置秘钥
        const uncrypted = decrypt.decrypt(value2);//解密之前拿公钥加密的内容

        setValue2(uncrypted);
    }, [value, value2, setValue2]);

    const onChange = useCallback((e) => {
        setValue(e.target.value);
    }, [setValue]);

    const onChange2 = useCallback((e) => {
        setValue2(e.target.value);
    }, [setValue2]);

    return (
        <div>
            <button onClick={handleSetStep}>step is : {step} </button>
            <button onClick={handleSetCount}>count is : {count} </button>
            <button onClick={handleCalNumber}>number is : {number} </button>
            <hr />
            <Child step={step} count={count} number={number} /> <hr />
            <ChildMemo step={step} count={count} number={number} />
            <hr />
            <textarea rows={10} value={value} onChange={onChange} style={{ width: '80%', height: '40%' }}></textarea>
            <hr />
            <button onClick={onEncode}>加密</button>
            <hr />
            <button onClick={onDecode}>解密</button>
            <hr />
            <textarea rows={10} onChange={onChange2} value={value2} style={{ width: '80%', height: '40%' }}></textarea>
        </div>
    );
};